<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header">{{ $route.query.id ? "试题修改" : "试题录入" }}</div>
      <!-- 放置表单组件 -->
      <el-form
        :model="subjects"
        :rules="rules"
        ref="subjectRef"
        label-width="100px"
      >
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            @change="changeSubject"
            v-model="subjects.subjectID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select
            placeholder="请选择"
            style="width: 400px"
            v-model="subjects.catalogID"
          >
            <el-option
              v-for="(item, index) in directoryList"
              :key="index"
              :label="item.directoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select
            placeholder="请选择"
            style="width: 400px"
            v-model="subjects.enterpriseID"
          >
            <el-option
              v-for="item in shortList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" required prop="province">
          <el-col :span="3.5">
            <el-select
              placeholder="请选择"
              style="width: 200px"
              v-model="subjects.province"
              @change="cityChoose"
            >
              <el-option
                v-for="(item, index) in provincesList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="1" style="margin-left: 1px">
            <el-select
              placeholder="请选择"
              style="width: 200px"
              v-model="subjects.city"
            >
              <el-option
                v-for="(item, index) in citysList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select placeholder="请选择" v-model="subjects.direction">
            <el-option
              v-for="(item, index) in directionList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="subjects.questionType">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="subjects.difficulty">
            <el-radio
              v-for="item in difficultyObj"
              :key="item.id"
              :label="item.label"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 富文本编辑框组件 -->
        <el-form-item label="题干：" prop="question">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden"
              v-model="subjects.question"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </el-form-item>
        <!-- 选项 -->
        <!-- 选中单选的时候 -->
        <div v-if="subjects.questionType === '1'">
          <el-form-item label="选项：">
            <el-radio-group v-model="subjects.options.code">
              <div v-for="item in subjects.options" :key="item.id">
                <el-row style="margin-top: 20px" type="flex" align="middle">
                  <el-radio :label="item" v-model="isRight">{{
                    item.code
                  }}</el-radio>
                  <el-input v-model="item.title" class="input-choose" />
                  <image-upload v-model="item.img"></image-upload>
                </el-row>
              </div>
            </el-radio-group>
            <el-row style="margin-top: 20px">
              <el-button type="danger" size="mini" disabled>
                +增加选项与答案
              </el-button>
            </el-row>
          </el-form-item>
        </div>
        <!-- 选中多选的时候 -->
        <div v-if="subjects.questionType === '2'">
          <el-form-item label="选项：">
            <el-radio-group v-model="subjects.options.code">
              <div v-for="item in subjects.options" :key="item.id">
                <el-row style="margin-top: 20px" type="flex" align="middle">
                  <el-checkbox
                    v-model="isRight"
                    :label="item"
                    style="margin-right: 30px"
                    >{{ item.code }}</el-checkbox
                  >
                  <el-input v-model="item.title" class="input-choose" />
                  <image-upload v-model="item.img"></image-upload>
                </el-row>
              </div>
            </el-radio-group>
            <el-row style="margin-top: 20px">
              <el-button type="danger" size="mini" @click="addFn">
                +增加选项与答案
              </el-button>
              <el-button type="info" size="mini" @click="jianFn">
                -点击删除选项
              </el-button>
            </el-row>
          </el-form-item>
        </div>
        <!-- 选中简答的时候 -->
        <div v-if="subjects.questionType === '3'"></div>
        <el-form-item label="解析视频：" prop="videoURL">
          <el-input style="width: 400px" v-model="subjects.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析：" prop="answer">
          <quillEditor
            style="height: 200px; margin-bottom: 60px"
            v-model="subjects.answer"
          ></quillEditor>
        </el-form-item>
        <el-form-item label="题目备注：" prop="remarks">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            size="medium"
            show-word-limit
            style="width: 400px"
            v-model="subjects.remarks"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="试题标签：" prop="tags">
          <el-select
            placeholder="请选择"
            style="width: 400px"
            v-model="subjects.tags"
          >
            <el-option
              v-for="(item, index) in tagsList"
              :key="index"
              :label="item.tagName"
              :value="item.tagName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="!$route.query.id" @click="submit()" type="primary"
            >确认提交</el-button
          >
          <el-button v-else @click="update()" type="success"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { list as getSubjectList } from '@/api/hmmm/subjects.js'
import { list as getDirectorysList } from '@/api/hmmm/directorys.js'
import { list as getCompanysList } from '@/api/hmmm/companys.js'
import { provinces as getProvincesList } from '@/api/hmmm/citys.js'
import { citys as getCitysList } from '@/api/hmmm/citys.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { list as getTagsList } from '@/api/hmmm/tags.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
//上传图片的组件
import imageUpload from './components/image-upload.vue'
export default {
  components: {
    Editor,
    Toolbar,
    quillEditor,
    imageUpload
  },
  data() {
    return {
      editor: null,
      html: '<p>hello</p>',
      toolbarConfig: {},
      toolbarConfig1: {},
      editorConfig: { placeholder: '请输入内容...' },
      editorConfig1: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
      mode1: 'default', // or 'simple'
      dialogImageUrl: '', //上传图片
      dialogVisible: false, //上传图片
      disabled: false, //上传图片
      subjectList: [], //学科
      directoryList: [], //目录
      shortList: [], //企业
      provincesList: [], //省份
      citysList: [], //城市
      directionList: [], //方向
      tagsList: [], //标签
      questionType: { 1: '单选', 2: '多选', 3: '简答' }, //	题目难度
      difficultyObj: { 1: '简单', 2: '一般', 3: '困难' }, //	题目难度
      count: 68,
      subjects: {
        subjectName: '',
        subjectID: null, //学科
        catalogID: null, //目录
        enterpriseID: null, //企业
        province: null, //城市
        city: null, //地区
        direction: null, //方向
        questionType: '1', //	题目类型:1(单选),2(多选),3(简答)
        difficulty: '简单', //	题目难度: 1(简单),2(一般),3(困难)
        question: '', //题干
        answer: '', //答案解析
        tags: '', //标签
        img: '',
        options: [
          { isRight: false, code: 'A:', title: '', img: '' },
          { isRight: false, code: 'B:', title: '', img: '' },
          { isRight: false, code: 'C:', title: '', img: '' },
          { isRight: false, code: 'D:', title: '', img: '' }
        ],
        videoURL: '', //解析视频
        remarks: '', //题目备注
        delivery: false
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [{ required: true, message: '请选择题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请选择解析', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getSubjectList(),
      this.getDirectorysList(),
      this.getCompanysList(),
      this.getProvincesList(), //城市
      // this.getTagsList(),
      this.getTagsList()
    // 调用接口获取题目信息
    if (this.$route.query.id) {
      this.getQuestion()
    }
    this.questionType = questionType
    this.directionList = direction
    this.difficultyObj = difficulty
  },
  methods: {
    //编辑----------------------------------------------------------------------------------------
    // 获取题目信息
    async getQuestion() {
      // 请求基础题库详情
      const { data } = await detail({ id: this.$route.query.id })
      console.log(data)
      // 标签数组
      data.tags = data.tags.split(',')
      // 选项
      data.options = data.options.map((item) => {
        item.isRight = item.isRight === 1
        return item
      })
      // 将获得数据赋值给表单
      this.subjects = data
      // 根据请求到的数据去请求目录标签
      const res = await getDirectorysList({
        subjectID: this.subjects.subjectID
      })
      this.catalogOptions = res.data //目录选项
      const res2 = await getTagsList({ subjectID: this.subjects.subjectID })
      this.tagsList = res2.data //标签选项
    },
    // 当学科发生改变时需要
    async changeSubject(subjectID) {
      this.subjects.catalogID = null //目录置空
      // 请求目录及标签
      const result = await getCatalogOptions({
        subjectID: this.subjects.subjectID
      })
      this.catalogOptions = result.data //目录选项
      this.subjects.tags = null //标签置空
      const result2 = await getTagsList({ subjectID: this.subjects.subjectID })
      this.tagsList = result2.data //标签选项
    },
    update() {
      //更新操作
      this.$refs.subjectRef.validate(async (valid) => {
        if (valid) {
          const data = { ...this.subjects }
          data.tags = data.tags.join(',')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    },
    //提交
    submit() {
      this.$refs.subjectRef.validate(async (isOk) => {
        if (isOk) {
          const data = { ...this.subjects }
          console.log(data)

          await add({ ...this.subjects })
          this.$message.success('新增成功')
          //跳转到列表页
          this.$router.push('/questions/list')
          this.subjects = {
            subjectID: null, //学科
            catalogID: null, //目录
            enterpriseID: null, //企业
            province: null, //城市
            city: null, //地区
            direction: null, //方向
            questionType: '1', //	题目类型:1(单选),2(多选),3(简答)
            difficulty: '简单', //	题目难度: 1(简单),2(一般),3(困难)
            question: '', //题干
            answer: '', //答案解析
            tags: '', //标签
            img: '',
            options: [
              { isRight: false, code: 'A:', title: '', img: '' },
              { isRight: false, code: 'B:', title: '', img: '' },
              { isRight: false, code: 'C:', title: '', img: '' },
              { isRight: false, code: 'D:', title: '', img: '' }
            ],
            videoURL: '', //解析视频
            remarks: '', //题目备注
            delivery: false
          }
        }
      })
    },

    //调用学科的接口
    async getSubjectList() {
      const { data } = await getSubjectList()
      this.subjectList = data.items
      console.log(data)
    },
    //调用目录的接口
    async getDirectorysList() {
      const { data } = await getDirectorysList()
      this.directoryList = data.items
      console.log(data.items)
    },
    //调用企业的接口
    async getCompanysList() {
      const { data } = await getCompanysList()
      this.shortList = data.items
      console.log(data.items)
    },
    //调用城市的接口
    async getProvincesList() {
      this.provincesList = await getProvincesList()
    },
    // 城市下地区
    cityChoose(e) {
      console.log(e)
      this.citysList = getCitysList(e)
      // console.log(this.citysList)
    },
    //标签
    async getTagsList() {
      const { data } = await getTagsList()
      this.tagsList = data.items
      console.log(this.tagsList)
    },
    //调用新增的接口
    addFn() {
      //给一个变量的值为68 ASCII码表的D开始点击的时候++
      this.count++
      this.subjects.options.push({
        isRight: false,
        code: String.fromCharCode(this.count),
        title: '',
        img: ''
      })
    },
    jianFn() {
      this.count--
      this.subjects.options.pop(
        {
          isRight: false,
          code: String.fromCharCode(this.count),
          title: '',
          img: ''
        },
        1
      )
    },
    //富文本编辑器1
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    mounted() {
      // 模拟 ajax 请求，异步渲染编辑器
      setTimeout(() => {
        this.html = '<p>请输入答案...</p>'
      }, 1500)
    },
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy() // 组件销毁时，及时销毁编辑器
    },
    //富文本编辑器2
    onCreated1(editor) {
      this.editor1 = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },

    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy() // 组件销毁时，及时销毁编辑器
    }
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-divider--horizontal {
  width: 100%;
}
//上传文件框设置宽高
// ::v-deep .el-upload--picture-card {
//   width: 100px;
//   height: 50px;
// }
// 输入框的长度
.input-choose {
  width: 260px;
  margin-right: 70px;
}
</style>
